﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using CodeDemon.Models;

namespace CodeDemon.Controllers {
	public class ControllerBase : Controller, IController {

		public static string CurrentLoggedInReviewUserEmail { get; set; }
		public static int CurrentLoggedInReviewUserID { get; set; }
		public static string CurrentLoggedInReviewUserSVNAuthor { get; set; }
		// TODO: This is a hack with the session
		public static Dictionary<string, string> SessionHash { get; set; }
		public static void SetLoggedInUser( string email ) {
			ReviewModel reviewModel = new ReviewModel();
			var currentUser = (from user in reviewModel.DAO.GetUserByEmail( email ) select user).FirstOrDefault();
			CurrentLoggedInReviewUserEmail = currentUser.ReviewUserEmail;
			CurrentLoggedInReviewUserID = (int)currentUser.UserID;
			CurrentLoggedInReviewUserSVNAuthor = currentUser.SVNAuthor;

			// TODO: This is a hack with the init
			var session = ( from vars in reviewModel.DAO.GetUserSessionByUserID(CurrentLoggedInReviewUserID) select vars);
			SessionHash = new Dictionary<string, string>();
			foreach( var sessionVar in session ) {
				SessionHash.Add( sessionVar.SessionVarName, sessionVar.SessionVarValue );
			}
		}


		public static void PopulateModel( ICodeDemonModel model ) {
			model.CurrentReviewUserEmail = CurrentLoggedInReviewUserEmail;
			model.CurrentReviewUserID = CurrentLoggedInReviewUserID;
			model.CurrentReviewUserSVNAuthor = CurrentLoggedInReviewUserSVNAuthor;
		}
	}

	/// <summary>
	/// Checks the User's authentication using FormsAuthentication
	/// and redirects to the Login Url for the application on fail
	/// </summary>
	public class RequiresAuthenticationAttribute : ActionFilterAttribute {

		public bool AjaxControllerAction { get; set; }
		public override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			//redirect if not authenticated
			if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
				if (AjaxControllerAction) {
					filterContext.HttpContext.Response.Redirect( "/CodeDemon/Content/Error.html", true );
				} else {
					//use the current url for the redirect
					string redirectOnSuccess = filterContext.HttpContext.Request.Url.ToString();
					
					//send them off to the login page
					string redirectUrl = string.Format("?ReturnUrl={0}", HttpContext.Current.Server.UrlEncode(redirectOnSuccess));
					string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;

					filterContext.HttpContext.Response.Redirect( loginUrl, true );
				}
			} else {
				ControllerBase.SetLoggedInUser( filterContext.HttpContext.User.Identity.Name);
			}

		}
	}
}
